package org.lzfto.flink.demo.system.security.entity;

import java.util.Date;

public class LoginTryLog {

	private String loginName; // 登录用户名
	private Date lastTryTime; // 最近一次尝试时间
	private Integer tryTimes; // 最近累计尝试次数
	private Date nextValidTtime; // 下一次可以尝试时间

	public LoginTryLog(String loginName, Date lastTryTime, Integer tryTimes) {
		super();
		this.loginName = loginName;
		this.lastTryTime = lastTryTime;
		this.tryTimes = tryTimes;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public Date getLastTryTime() {
		return lastTryTime;
	}

	public void setLastTryTime(Date lastTryTime) {
		this.lastTryTime = lastTryTime;
	}

	public Integer getTryTimes() {
		return tryTimes;
	}

	public void setTryTimes(Integer tryTimes) {
		this.tryTimes = tryTimes;
	}

	public Date getNextValidTtime() {
		return nextValidTtime;
	}

	public void setNextValidTtime(Date nextValidTtime) {
		this.nextValidTtime = nextValidTtime;
	}

	public boolean isOverTryTimes(int maxTryTimes) {
		// 如果在 3秒钟之内尝试次数超过n次，则表示攻击，这个时候需要设置一个冷却时间，例如3分钟
		return this.tryTimes > maxTryTimes;
	}

	public void Try(int maxTryTimes) throws Exception {
		Date now = new Date();
		long threeMinutesInMillis = 3 * 60 * 1000;

		// 如果是第一次尝试或者超过三分钟没有尝试，重置计数器
		if (lastTryTime == null || (now.getTime() - lastTryTime.getTime()) > threeMinutesInMillis) {
			this.tryTimes = 1;
			this.lastTryTime = now;
			this.nextValidTtime = null;
			return;
		} else {
			// 在三分钟时间窗口内
			this.tryTimes++;
			this.lastTryTime = now;
		}

		// 检查是否超过最大尝试次数
		if (this.tryTimes > maxTryTimes) {
			// 设置下次可尝试时间为3分钟后
			this.nextValidTtime = new Date(now.getTime() + threeMinutesInMillis);
			throw new Exception("登录尝试次数过多，请" + threeMinutesInMillis / 60000 + "分钟后再试");
		}
	}

}
